
#ifndef __SHM_HPP__
#define __SHM_HPP__

#include <iostream>
#include <string>
#include <sys/ipc.h>
#include <cerrno>
#include <cstdio>
#include <sys/shm.h>
#include <unistd.h>
#include <cstdlib>
#include <cstring>

const std::string g_pathname = "/home/exercise/learn/linux-exer/communication/SharedMemory";
const int g_proj_id = 0x66;
const int gCreater = 1;
const int gUser = 2;
const int gShmSize = 4096;

class Shm
{
private:
    int GetShmHelper(key_t key, int size, int flag)
    {
        int shmid = shmget(key, size, flag);
        if (shmid < 0)
        {
            perror("shmget");
        }
        return shmid;
    }

    key_t GetCommKey()
    {
        key_t k = ftok(_pathname.c_str(), _proj_id);
        if (k < 0)
        {
            perror("ftok");
        }
        return k;
    }

    std::string RoleToString()
    {
        if (_who == gCreater) return "Creater";
        else if (_who == gUser) return "User";
        else return "None";
    }

    void* AttachShm()
    {
        void* shmaddr = shmat(_shmid, nullptr, 0);
        if (shmaddr == (void*) -1)
        {
            perror("shmat");
        }
        std::cout << "who: " << RoleToString() << " attach shm ..." << std::endl;
        return shmaddr;
    }

    void DetchShm(void* shmaddr)
    {
        if (shmaddr == nullptr) return;
        shmdt(shmaddr);
        std::cout << "who: " << RoleToString() << " detach shm ..." << std::endl;
    }

public:
    Shm(const std::string &pathname, int proj_id, int who)
        : _pathname(pathname), _proj_id(proj_id), _who(who), _addrshm(nullptr)
    {
        _key = GetCommKey();
        if (_who == gCreater) GetShmForCreate();
        else if (_who == gUser) GetShmForUse();

        std::cout << "shmid: " << _shmid << std::endl;
        std::cout << "key: " << ToHex() << std::endl;

        _addrshm = AttachShm();
    }

    std::string ToHex()
    {
        char buffer[128];
        snprintf(buffer, sizeof buffer, "0x%x", _key);
        return buffer;
    }

    bool GetShmForCreate()
    {
        if (_who == gCreater)
        {
            _shmid = GetShmHelper(_key, gShmSize, IPC_CREAT | IPC_EXCL | 0666);
            if (_shmid >= 0) 
            {
                std::cout << "Shm create done..." << std::endl;
                return true;
            }
        }
        return false;
    }

    bool GetShmForUse()
    {
        if (_who == gUser)
        {
            _shmid = GetShmHelper(_key, gShmSize, IPC_CREAT | 0666);
            if (_shmid >= 0)
            {
                std::cout << "Shm get done..." << std::endl;
                return true;
            }
        }
        return false;
    }

    void* Addr()
    {
        return _addrshm;
    }

    void Zero()
    {
        if (_addrshm)
        {
            memset(_addrshm, 0, gShmSize);
        }
    }

    void DebugShm()
    {
        struct shmid_ds ds;
        int n = shmctl(_shmid, IPC_STAT, &ds);
        if (n < 0) return;
        std::cout << "ds.shm_perm.__key: " << ds.shm_perm.__key << std::endl;
        std::cout << "ds.shm_nattch: " << ds.shm_nattch << std::endl;
    }

    ~Shm()
    {
        if (_addrshm != nullptr) DetchShm(_addrshm);
        if (_who == gCreater)
        {
            int res = shmctl(_shmid, IPC_RMID, nullptr);
            if (res >= 0)
                std::cout << "Shm remove done..." << std::endl;
        }
    }

private:
    key_t _key;
    int _shmid;
    std::string _pathname;
    int _proj_id;
    int _who; // 表明身份，创建或使用
    void* _addrshm;
};

#endif
